package com.sunny.excel.config.resolver;


import com.sunny.excel.annotation.ExcelFile;
import com.sunny.excel.excel.uploader.ExcelUploadManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.apache.commons.io.FilenameUtils;


import java.util.List;

public class ExcelFileArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired private ExcelUploadManager excelUploadManager;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(ExcelFile.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        ExcelFile excelFile = parameter.getParameterAnnotation(ExcelFile.class);
        try {
            MultipartRequest request = webRequest.getNativeRequest(MultipartRequest.class);
            MultipartFile file = request.getFile(excelFile.value());

            String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());

            String[] contextParamNames = excelFile.contextParam();

            String[] contextParam = null;

            if (contextParamNames != null && contextParamNames.length > 0) {
                contextParam = new String[contextParamNames.length];
                for (int i = 0; i < contextParamNames.length; i++) {
                    contextParam[i] = webRequest.getParameter(contextParamNames[i]);
                }
            }
            List<?> records =
                excelUploadManager.process(fileExt, file.getInputStream(), 0, excelFile.dataClass(), contextParam);
            return records;
        } catch (Exception ex) {

            throw ex;
        }
    }
}
